﻿using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Mail;
using System.Net;
using Logistics.Commn.RabbitMQ;
using Newtonsoft.Json;
using ServiceStack;
using Logistics.Commn;

namespace HS.RealEstate.RabbitMQ
{
    /// <summary>
    /// 路由模式它会把消息路由到那些 binding key 与 routing key 完全匹配的 Queue 中
    /// </summary>
    public class RecevieRouting
    {
        public static void DirectConsumer()
        {
            string queueName = "direct_errorlog";
            var connection = RabbitMQHelper.GetConnection();
            {
                //创建信道
                var channel = connection.CreateModel();
                {
                    //创建队列
                    channel.QueueDeclare(queueName, durable: true, exclusive: false, autoDelete: false,
                        arguments: null);
                    var consumer = new EventingBasicConsumer(channel);
                    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: true);

                    consumer.Received += (model, ea) =>
                    {
                        //处理业务
                        var message = Encoding.UTF8.GetString(ea.Body.ToArray());
                        var mess = Newtonsoft.Json.JsonConvert.DeserializeObject<Mail>(message);
                        EmailHelper.SendMailResetPwd(mess.AccountNumber, mess.Mailbox, mess.RandomNumber);
                        channel.BasicAck(ea.DeliveryTag, false); //消息ack确认，告诉mq这条队列处理完，可以从mq删除了
                    };
                    channel.BasicConsume(queueName, autoAck: false, consumer);
                }
            }
        }
    }
}